package io.github.harmonly.skyblock.listener;

import io.github.harmonly.skyblock.manager.DataManager;
import io.github.harmonly.skyblock.manager.ResourcesManager;
import io.github.harmonly.skyblock.type.Rank;
import io.github.harmonly.skyblock.util.Replacer;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerArmorStandManipulateEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.util.Vector;

public class PlayerListener implements Listener {

    @EventHandler
    public void onPlayerDamage(EntityDamageEvent event) {
        // 检查事件是否涉及玩家
        if (event.getEntity() instanceof Player player) {
            // 计算玩家受到伤害后的生命值
            double finalHealth = player.getHealth() - event.getFinalDamage();

            // 如果最终生命值小于等于 0，取消事件并将玩家传送到出生点
            if (finalHealth <= 0) {
                event.setCancelled(true); // 取消伤害事件
                player.teleport(player.getWorld().getSpawnLocation()); // 传送玩家到出生点
                player.setHealth(player.getMaxHealth()); // 恢复玩家的生命值
                player.playSound(player, Sound.ENTITY_PLAYER_DEATH, 1, 1);
                player.setArrowsInBody(0);
                player.setFireTicks(0);
                player.setVelocity(new Vector());
                player.setNoDamageTicks(20);
                player.sendMessage("§c你受到了致命伤害，被传送回出生点。");
            }
        }
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        DataManager.addPlayerData(player);

        DataManager.getPlayerData(player).ifPresent(playerData -> {
            // last join
            playerData.addProperty("lastLogin", System.currentTimeMillis());

            // join message
            Rank rank = Rank.getRank(playerData.getHighestRank());
            if (rank.ordinal() >= Rank.MVP_PLUS.ordinal()) {
                String joinMessage = Replacer.replaceIn(
                        ResourcesManager.getJson("message")
                                .getStringProperty("listener.player_join", event.getJoinMessage()),
                        "player", player.getDisplayName()
                );
                if (rank.ordinal() >= Rank.SUPERSTAR.ordinal()) {
                    joinMessage = "§b>§c>§a>§r " + joinMessage + " §r§a<§c<§b<";
                }

                player.sendMessage(joinMessage);
                for (Player p : player.getWorld().getPlayers()) {
                    p.sendMessage(joinMessage);
                }
            }
        });
        event.setJoinMessage(null);
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        Player player = event.getPlayer();
        DataManager.getPlayerData(player).ifPresent(playerData -> {
            playerData.addProperty("lastLogout", System.currentTimeMillis());
            DataManager.savePlayerData(player);
            DataManager.saveProfileData(player);
        });
    }

    @EventHandler
    public void onFood(FoodLevelChangeEvent event) {
        event.setCancelled(true);
    }

    @EventHandler
    public void onChat(AsyncPlayerChatEvent event) {
        DataManager.getPlayerData(event.getPlayer()).ifPresent(playerData -> {
            event.setFormat("%1$s" + (playerData.hasRank() ? "§f" : "") + ": %2$s");
        });
    }

    @EventHandler
    public void on(PlayerArmorStandManipulateEvent event) {
        event.setCancelled(true);
    }
}
